<?php
namespace forpc\controllers;


use common\components\Common;
use common\models\English;
use common\models\User;
use common\models\UserPractices;
use Yii;
use common\components\Controller;
use common\components\PageView;
use common\models\Category;
use common\models\Favorite;
use yii\db\Query;

/**
 * PractiseController
 */
class PracticeController extends Controller{

    public $enableCsrfValidation = false;

    public function actionIndex(){

        //用户ID
        $uid = $this->loginUid;
        if(empty($uid)){
            exit("未登录");
        }

        $searchtext = isset($_GET["searchtext"]) ? addslashes($_GET["searchtext"]) : "";
        $transtext = isset($_GET["transtext"]) ? addslashes($_GET["transtext"]) : "";
        $graduated = isset($_GET["graduated"]) ? intval($_GET["graduated"]) : 1;
        $mobile = (isset($_GET["mobile"]) && strtolower($_GET["mobile"]) != 'false') ? true : false;

        $categorys = \common\models\Category::getData();
        //print_r($categorys);

        $treeData = \common\models\Category::getTree($categorys);
        //print_r($treeData);

        $where = " WHERE TRUE";
        $con_searchtext = (empty($searchtext)) ? "" : " AND e.word LIKE '%".$searchtext."%'";
        $con_transtext = (empty($transtext)) ? "" : " AND e.trans LIKE '%".$transtext."%'";
        $con2 = ($graduated == 1) ? " AND p.express_correct<16" : "";
        $where = $where.$con_searchtext.$con_transtext.$con2;

        $db = Yii::$app->db;
        $sql = 'SELECT count(*) FROM {{%english}} AS e'.
            " LEFT JOIN {{%user_practices}} AS p ON e.id=p.eid".
            $where;
        //echo $db->createCommand($sql)->getRawSql();exit;
        $dataCount = $db->createCommand($sql)->queryScalar();

        $allword = $db->createCommand("SELECT count(*) FROM {{%user_practices}}")->queryScalar();//收藏总量

        //毕业
        $graduatedcount = UserPractices::find()->where(["uid"=>$uid])->andWhere(['>=', 'express_correct', 16])->count();


        //破冰
        $icebreaking = UserPractices::find()->where(["uid"=>$uid])->andWhere(['>', 'express_correct', 0])->count();

        $perPage = 20;
        $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;

        $pv = new PageView($dataCount, $perPage, $currentPage);

        $sql = 'SELECT e.id, e.cid,'.
            't.name AS cname, c2.name AS cname2, e.word, e.ipa_en, e.ipa_us, e.trans, p.express_correct,p.express_correct_at FROM {{%english}} AS e '.
            ' LEFT JOIN {{%user_practices}} AS p ON e.id=p.eid'.
            ' LEFT JOIN {{%knowledge_cate}} AS t ON e.c1=t.id '.
            ' LEFT JOIN {{%knowledge_cate}} AS c2 ON e.c2=c2.id '.
            $where." ORDER BY e.displayorder ASC".$pv->limitSql;

        $favorite = $db->createCommand($sql)->queryAll();

        $data = [
            "searchtext" => $searchtext,
            "transtext" => $transtext,
            "categorys" => $categorys,
            'treeData' => $treeData,
            "graduated" => $graduated,
            "favorite"=> $favorite,
            "pv"=>$pv,
            "mobile"=>$mobile,
            "allword" => $allword,
            "icebreaking" => $icebreaking,
            "graduatedcount" => $graduatedcount,
        ];

        if($mobile){
            return $this->renderPartial('mobile', $data);
        }else{
            return $this->renderPartial('index', $data);
        }

    }

    /**
     * 理解模式
     * @return string
     * @throws \yii\db\Exception
     */
    public function actionUnderstand(){

        //用户ID
        $uid = $this->loginUid;
        if(empty($uid)){
            exit("未登录");
        }

        $searchtext = isset($_GET["searchtext"]) ? addslashes($_GET["searchtext"]) : "";
        $transtext = isset($_GET["transtext"]) ? addslashes($_GET["transtext"]) : "";
        $graduated = isset($_GET["graduated"]) ? intval($_GET["graduated"]) : 1;
        $mobile = (isset($_GET["mobile"]) && strtolower($_GET["mobile"]) != 'false') ? true : false;

        $where = " WHERE TRUE";
        $con_searchtext = (empty($searchtext)) ? "" : " AND e.word LIKE '%".$searchtext."%'";
        $con_transtext = (empty($transtext)) ? "" : " AND e.trans LIKE '%".$transtext."%'";
        $con2 = ($graduated == 1) ? " AND (p.understand_correct<16 OR p.understand_correct is NULL)" : "";
        $where = $where.$con_searchtext.$con_transtext.$con2;

        $db = Yii::$app->db;
        $sql = 'SELECT count(*) FROM {{%english}} AS e'.
            " LEFT JOIN {{%user_practices}} AS p ON e.id=p.eid".
            $where;
        //echo $db->createCommand($sql)->getRawSql();exit;
        $dataCount = $db->createCommand($sql)->queryScalar();

        //毕业
        $graduatedcount = UserPractices::find()->where(["uid"=>$uid])->andWhere(['>=', 'understand_correct', 16])->count();

        //破冰
        $icebreaking = UserPractices::find()->where(["uid"=>$uid])->andWhere(['>', 'understand_correct', 0])->count();


        $perPage = 20;
        $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;

        $pv = new PageView($dataCount, $perPage, $currentPage);

        $sql = 'SELECT e.id, e.cid,'.
            't.name AS cname, c2.name AS cname2, e.word, e.ipa_en, e.ipa_us, e.trans, p.understand_correct,p.understand_correct_at FROM {{%english}} AS e '.
            ' LEFT JOIN {{%user_practices}} AS p ON e.id=p.eid AND p.uid='.$uid.
            ' LEFT JOIN {{%knowledge_cate}} AS t ON e.c1=t.id '.
            ' LEFT JOIN {{%knowledge_cate}} AS c2 ON e.c2=c2.id '.
            $where." ORDER BY e.displayorder ASC".$pv->limitSql;

        $favorite = $db->createCommand($sql)->queryAll();

        //echo '<pre>';print_r($favorite);exit;

        $data = [
            "searchtext" => $searchtext,
            "transtext" => $transtext,
            "graduated" => $graduated,
            "favorite"=> $favorite,
            "pv"=>$pv,
            "mobile"=>$mobile,
            "allword" => $dataCount,
            "icebreaking" => $icebreaking,
            "graduatedcount" => $graduatedcount,
        ];

        if($mobile){
            return $this->renderPartial('understand-mobile', $data);
        }else{
            return $this->renderPartial('understand', $data);
        }

    }

    /**
     * 把顺序放到最后
     * @throws \yii\db\Exception
     */
    public function actionAsyncLast(){
        try{
            //当前单词ID
            $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
            if(empty($id) || $id <= 0){
                exit(json_encode(["code"=>-1, "info"=>"缺少参数知识ID"], JSON_UNESCAPED_UNICODE));
            }

            //最后的顺序
            $last = Favorite::getLastOrder();


            $data = [
                "displayorder" => $last+1,
                "update_time" => time(),
            ];
            $line = Yii::$app->db->createCommand()->update('{{%english}}', $data, 'id='.$id)->execute();
            if($line == 1){
                exit(json_encode(["code"=>1, "info"=>"成功"], JSON_UNESCAPED_UNICODE));
            }else{
                exit(json_encode(["code"=>-5, "info"=>"失败"], JSON_UNESCAPED_UNICODE));
            }
        }catch(\Exception $e){
            exit(json_encode(["code"=>-5, "info"=>"数据操作异常".$e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 知识交换
     */
    public function actionExchange(){
        return $this->renderPartial('exchange');
    }

    /**
     * 知识交换
     */
    public function actionAsyncExchange(){
        $id1 = isset($_GET["id1"]) ? intval($_GET["id1"]) : 0;
        $id2 = isset($_GET["id2"]) ? intval($_GET["id2"]) : 0;

        if(empty($id1) || empty($id2)){
            exit(json_encode(["code"=>-1, "info"=>"参数错误"], JSON_UNESCAPED_UNICODE));
        }

        try{
            Favorite::exchange($id1, $id2);
        }catch(\Exception $e){
            exit(json_encode(["code"=>-2, "info"=>$e->getMessage()], JSON_UNESCAPED_UNICODE));
        }

        exit(json_encode(["code"=>1, "info"=>"交换成功"], JSON_UNESCAPED_UNICODE));

    }

    /**
     * 与上边相邻的数据交换顺序
     */
    public function actionAsyncExchangeAbove(){
        $transaction = Yii::$app->db->beginTransaction();
        try{

            //当前ID
            $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
            if(empty($id)){
                exit(json_encode(["code"=>-1, "info"=>"参数错误"], JSON_UNESCAPED_UNICODE));
            }

            //哪个顺序
            $order = isset($_GET["order"]) ? addslashes($_GET["order"]) : "express";
            if(!in_array($order, ['express', 'understand'])){
                $order = 'express';
            }

            /**
             * @var English $english 当前单词对象
             */
            $english = English::find()->where(["id"=>$id])->one();
            if(empty($english)){
                exit(json_encode(["code"=>500, "info"=>"单词不存在"], JSON_UNESCAPED_UNICODE));
            }

            //当前单词的顺序
            $tempOrder = $english->displayorder;

            /**
             * @var English $above
             */
            $sql = "SELECT e.id FROM `en_english` AS e".
                " LEFT JOIN `en_user_practices` AS p ON e.id=p.eid".
                " WHERE e.displayorder<".$tempOrder." AND p.".$order."_correct<16 ORDER BY e.displayorder DESC LIMIT 1";
            $aboveId = Yii::$app->db->createCommand($sql)->queryScalar();
            $above = English::find()->where(["id"=>$aboveId])->one();
            if(empty($above)){
                exit(json_encode(["code"=>400, "info"=>"顺序已最前"], JSON_UNESCAPED_UNICODE));
            }

            //交换顺序
            $english->displayorder = $above->displayorder;
            $above->displayorder = $tempOrder;
            if(!$english->save() || !$above->save()){
                $transaction->rollBack();
                exit(json_encode(["code"=>500, "info"=>"顺序交换失败"], JSON_UNESCAPED_UNICODE));
            }

            $transaction->commit();
            exit(json_encode(["code"=>200, "成功"], JSON_UNESCAPED_UNICODE));

        }catch (\Exception $e){
            $transaction->rollBack();
            exit(json_encode(["code"=>500, "失败", "data"=>$e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 理解模式回答正确
     * @throws \yii\db\Exception
     */
    public function actionExpressCorrect(){
        $transaction = Yii::$app->db->beginTransaction();
        try{

            $uid = $this->loginUid;
            if(empty($uid)){
                exit(json_encode(["code"=>-1, "info"=>"未登录"], JSON_UNESCAPED_UNICODE));
            }

            //当前ID
            $eid = isset($_GET["eid"]) ? intval($_GET["eid"]) : 0;
            if(empty($eid)){
                exit(json_encode(["code"=>-1, "info"=>"参数错误"], JSON_UNESCAPED_UNICODE));
            }

            $curtime = time();

            //用户练习
            $practice = UserPractices::find()->where(["uid"=>$uid, "eid"=>$eid])->one();
            if(empty($practice)){
                $practice = new UserPractices();
                $practice->uid = $uid;
                $practice->eid = $eid;
                $practice->create_time = $curtime;
            }

            //时间
            $locktime = Common::getLocktime($practice->express_correct);
            if($practice->express_correct_at + $locktime > $curtime){
                exit(json_encode(["code"=>-2, "info"=>"距离上次操作不超过".($locktime/3600)."小时，请稍后再试"], JSON_UNESCAPED_UNICODE));
            }

            $practice->express_correct = intval($practice->express_correct)+1;
            $practice->express_correct_at = time();
            $practice->update_time = time();
            if(!$practice->save()){
                print_r($practice->getErrors());
                exit(json_encode(["code"=>500, "info"=>"保存失败"], JSON_UNESCAPED_UNICODE));
            }

            $transaction->commit();
            exit(json_encode(["code"=>200, "成功"], JSON_UNESCAPED_UNICODE));

        }catch (\Exception $e){
            $transaction->rollBack();
            exit(json_encode(["code"=>500, "失败", "data"=>$e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
    }

    public function actionExpressWrong(){
        $transaction = Yii::$app->db->beginTransaction();
        try{

            $uid = $this->loginUid;
            if(empty($uid)){
                exit(json_encode(["code"=>-1, "info"=>"未登录"], JSON_UNESCAPED_UNICODE));
            }

            //当前ID
            $eid = isset($_GET["eid"]) ? intval($_GET["eid"]) : 0;
            if(empty($eid)){
                exit(json_encode(["code"=>-1, "info"=>"参数错误"], JSON_UNESCAPED_UNICODE));
            }

            $curtime = time();

            //用户练习
            $practice = UserPractices::find()->where(["uid"=>$uid, "eid"=>$eid])->one();
            if(empty($practice)){
                $practice = new UserPractices();
                $practice->uid = $uid;
                $practice->eid = $eid;
                $practice->create_time = $curtime;
            }

            if(intval($practice->express_correct) <= 0){
                exit(json_encode(["code"=>400, "info"=>"已经最低，不能再降"], JSON_UNESCAPED_UNICODE));
            }

            $practice->express_correct = intval($practice->express_correct)-1;
            $practice->update_time = time();
            if(!$practice->save()){
                print_r($practice->getErrors());
                exit(json_encode(["code"=>500, "info"=>"保存失败"], JSON_UNESCAPED_UNICODE));
            }

            $transaction->commit();
            exit(json_encode(["code"=>200, "成功"], JSON_UNESCAPED_UNICODE));

        }catch (\Exception $e){
            $transaction->rollBack();
            exit(json_encode(["code"=>500, "失败", "data"=>$e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 理解模式回答正确
     * @throws \yii\db\Exception
     */
    public function actionUnderstandCorrect(){
        $transaction = Yii::$app->db->beginTransaction();
        try{

            $uid = $this->loginUid;
            if(empty($uid)){
                exit(json_encode(["code"=>-1, "info"=>"未登录"], JSON_UNESCAPED_UNICODE));
            }

            //当前ID
            $eid = isset($_GET["eid"]) ? intval($_GET["eid"]) : 0;
            if(empty($eid)){
                exit(json_encode(["code"=>-1, "info"=>"参数错误"], JSON_UNESCAPED_UNICODE));
            }

            $curtime = time();

            //用户练习
            $practice = UserPractices::find()->where(["uid"=>$uid, "eid"=>$eid])->one();
            if(empty($practice)){
                $practice = new UserPractices();
                $practice->uid = $uid;
                $practice->eid = $eid;
                $practice->create_time = $curtime;
            }

            //时间
            $locktime = Common::getLocktime($practice->understand_correct);
            if($practice->understand_correct_at + $locktime > $curtime){
                exit(json_encode(["code"=>-2, "info"=>"距离上次操作不超过".($locktime/3600)."小时，请稍后再试"], JSON_UNESCAPED_UNICODE));
            }

            $practice->understand_correct = intval($practice->understand_correct)+1;
            $practice->understand_correct_at = time();
            $practice->update_time = time();
            if(!$practice->save()){
                print_r($practice->getErrors());
                exit(json_encode(["code"=>500, "info"=>"保存失败"], JSON_UNESCAPED_UNICODE));
            }

            $transaction->commit();
            exit(json_encode(["code"=>200, "成功"], JSON_UNESCAPED_UNICODE));

        }catch (\Exception $e){
            $transaction->rollBack();
            exit(json_encode(["code"=>500, "失败", "data"=>$e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
    }

    public function actionUnderstandWrong(){
        $transaction = Yii::$app->db->beginTransaction();
        try{

            $uid = $this->loginUid;
            if(empty($uid)){
                exit(json_encode(["code"=>-1, "info"=>"未登录"], JSON_UNESCAPED_UNICODE));
            }

            //当前ID
            $eid = isset($_GET["eid"]) ? intval($_GET["eid"]) : 0;
            if(empty($eid)){
                exit(json_encode(["code"=>-1, "info"=>"参数错误"], JSON_UNESCAPED_UNICODE));
            }

            $curtime = time();

            //用户练习
            $practice = UserPractices::find()->where(["uid"=>$uid, "eid"=>$eid])->one();
            if(empty($practice)){
                $practice = new UserPractices();
                $practice->uid = $uid;
                $practice->eid = $eid;
                $practice->create_time = $curtime;
            }

            if(intval($practice->understand_correct) <= 0){
                exit(json_encode(["code"=>400, "info"=>"已经最低，不能再降"], JSON_UNESCAPED_UNICODE));
            }

            $practice->understand_correct = intval($practice->understand_correct)-1;
            $practice->update_time = time();
            if(!$practice->save()){
                print_r($practice->getErrors());
                exit(json_encode(["code"=>500, "info"=>"保存失败"], JSON_UNESCAPED_UNICODE));
            }

            $transaction->commit();
            exit(json_encode(["code"=>200, "成功"], JSON_UNESCAPED_UNICODE));

        }catch (\Exception $e){
            $transaction->rollBack();
            exit(json_encode(["code"=>500, "失败", "data"=>$e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
    }

}
